<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="编辑素材" width="650px" @ok="handleSubmit"
    showFooter destroyOnClose>
    <BasicForm @register="registerForm">
      <!-- <template #fileSizeLimit="{ model, field }">
        <a-input v-model:value="model[field]" placeholder="请输入限制大小" suffix="KB" />
      </template> -->
    </BasicForm>

  </BasicDrawer>
</template>
<script lang="ts" setup>
import {ref, unref, useAttrs} from 'vue';
import {BasicForm, useForm} from '/@/components/Form';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {materialFormSchema} from '../material.data';
import {saveOrUpdateMaterial} from '../material.api';
import {listDataGroupTree} from '/@/api/infra/dataGroup.ts';
import {DataGroupBizType} from '/@/api/infra/model/dataGroup.ts';
import {useMessage} from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelCol: {
    md: { span: 4 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 18 },
  },
  
  labelWidth: 80,
  schemas: materialFormSchema,
  showActionButtonGroup: false
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  console.log('data', data);
  
  setDrawerProps({ confirmLoading: false });
  //获取下拉树信息
  const treeData = await listDataGroupTree({ bizType:  DataGroupBizType.MATERIAL, groupType: data.materialType});

  updateSchema([
    {
      field: 'groupId',
      componentProps: { treeData },
    }, 
    {
      field: 'url',
      componentProps: { 
        maxCount: 1,
        accept: data.fileTypeLimit
      }
    },
  ])

  if (unref(isUpdate)) {
    setFieldsValue({ ...data.record });
  }

});


/**
 * 提交
 */
async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });

    const form : any = {...values}
    console.log("form: ", form);
    await saveOrUpdateMaterial(form, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`编辑成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
